package com.xianyun.site.iblog.gatewayimpl.common;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author mac_zyj
 */
@Slf4j
@Component
public class BaseSupportGatewayImpl {
    @Autowired
    private RocketMQTemplate rocketMq;


    protected  Response sendMessage(String messageString,String transactionId,String destination){
        //构建消息体
        Message<String> message = MessageBuilder.withPayload(messageString)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                .setHeaderIfAbsent(RocketMQHeaders.TAGS,"COSTUMER").build();
        SendResult sendResult=rocketMq.syncSend(destination, message);
        log.info("send transactional message body={},result={}",message.getPayload(),sendResult.getSendStatus());
        if (sendResult.getSendStatus().equals(SendStatus.SEND_OK)){
            return Response.buildSuccess();
        }
        throw new BizException("发送失败");
    }
}
